package com.gm.tool.system;

import android.util.Log;

import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;

/**
 * Created by Mouse on 2016/11/15.
 */

public class RootShellCmd {

    private DataOutputStream os = null;

    public RootShellCmd() throws IOException {

        Process process = createSuProcess();
        if (process != null && os == null) {
            os = new DataOutputStream(process.getOutputStream());
        } else {
            Log.w("RootShellCmd", "获取ROOT权限失败");
        }

    }

    private Process createSuProcess() throws IOException {
        File rootUser = new File("/system/xbin/ru");
        if (rootUser.exists()) {
            return Runtime.getRuntime().exec(rootUser.getAbsolutePath());
        } else {
            return Runtime.getRuntime().exec("su");
        }
    }

    public RootShellCmd exec(String cmd) throws IOException {
        if (os != null) {
            os.writeBytes(cmd + "\n");
            os.flush();
        }
        return this;
    }

    public void execAndClose(String cmd) throws IOException {
        if (os != null) {
            os.writeBytes(cmd + "\n");
            os.flush();
            close();
        }
    }

    public void close() throws IOException {
        if (os != null) {
            os.writeBytes("exit $?\n");
            os.flush();
            os.close();
            os = null;
        }
    }

}
